define(['moment', 'module/system/service/WatchDogService', 'module/moduleB/program/B0301/abnormal_detail'], function () {
    return ['$scope', '$filter', '$mdDialog', '$stateParams', 'config', 'MMWService', '$timeout', 'WatchDogService', '$mdlToast', 'AbnormalService', '$calculater', '$compile',
    function ($scope, $filter, $mdDialog, $stateParams, config, $MMWService, $timeout, $WatchDogService, $mdlToast, $AbnormalService, $calculater, $compile) {
        var stationMachineInfo;
        var ESOPSIze, chatHub;
        var shell;
        // 需要使用外部瀏覽器開啟的連結前綴清單
        var externalLinkPrefixList = ['http'];
        // 20230321 modify by Alan for#: 一體化卡控,eSOP功能從PTC_SOP移動至SOP_PLM
        $scope.SOP_PLM = config.cache.module_setting.SOP_PLM;
        $scope.isESOPSize = '';
        $scope._fn = {
            'E08_confirm':{
                click:()=>{
                    $scope.confirm();
                }
            }
        }
        $scope.dynamicFormLoaded = function(){
            $scope.plotItem = {
                op_no: "",
                plot_no: "",
                pcs_no:"",
                station_no: ""
            }
            //$scope.feedingOpionOn = (config.cache.sys_parameter.MaterialFeedingOption == '1');
            $scope.stationMachine = {};
            if(window.cordova){
                document.getElementById('input_barcode').readOnly = true;
            }
            try {
                shell = window.nodeRequire('electron').shell;
            } catch(e) {
                shell = null;
            }
            $(window).bind('blur', focus_window);
            if($stateParams.data){
                $scope.stationMachine = $stateParams.data;
                $scope.stationMachine.validate_mode = 0;
                //20190916 add by Dustdusk for M#61062:工位機物料設定權限
                if(!config.cache.permissions || config.cache.permissions.indexOf('E05')!=-1){
                    $scope.stationMachine.showE05 = true;
                } else {
                    $scope.stationMachine.showE05 = false;
                }
                $scope.confirm();
            } else {
                stationMachineInfo = localStorage.getItem(config.appName + '_stationMachine_op');
                if(stationMachineInfo){
                    stationMachineInfo = JSON.parse(stationMachineInfo);
                    $scope.stationMachine = stationMachineInfo;
                    $scope.stationMachine.validate_mode = 0;
                     // 20231205 add by shiwl for M#  0151031: 作业站序号收集 初次进入 保存单笔确认，无法保存配置
                    $scope.E08_single_confirm = $scope.stationMachine.single_confirm ? "0":"1";
                    //20190916 add by Dustdusk for M#61062:工位機物料設定權限
                    if(!config.cache.permissions || config.cache.permissions.indexOf('E05')!=-1){
                        $scope.stationMachine.showE05 = true;
                    } else {
                        $scope.stationMachine.showE05 = false;
                    }
                    $scope.confirm();
                } else {
                    $scope.mode = 'setting';
                }
            }
        };

        $scope.back = function(){
            $scope.final(function(){
                $scope.$root.changeProgram('home', true);
            });
        };

        $scope.final = function(callback){
            if($scope.selectItem && $scope.selectItem.pcs_detail
                && $scope.selectItem.pcs_detail.length > 0){
                //當切換一筆的時候要提示
                $scope.$root.showConfirm($filter('translate')('E08.msg.closeAlert'), function(dialog){
                    dialog.hide();
                    stopSignalR(function(){
                        if(stationMachineInfo)
                            $WatchDogService.stopWatch();

                        //20181018 add by Dustdusk for M#:
                        $scope.disconnection = false;
                        if(refresh_timer != undefined){
                            $timeout.cancel(refresh_timer);
                            refresh_timer = undefined;
                        }
                        //config.setting.RefreshTime = RefreshTime;
                        $(window).unbind('blur', focus_window);
                        if(typeof callback === 'function')
                            callback();
                    });
                }, function(dialog){
                    dialog.hide();
                    // 20220316 modify by chenshibo for#108564: 提示点取消，侧边栏消失
                    $scope.$root.selectHome = false;
                });
            } else {
                stopSignalR(function(){
                    if(stationMachineInfo)
                        $WatchDogService.stopWatch();

                    //20181018 add by Dustdusk for M#:
                    $scope.disconnection = false;
                    if(refresh_timer != undefined){
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                    }
                    //config.setting.RefreshTime = RefreshTime;
                    $(window).unbind('blur', focus_window);
                    if(typeof callback === 'function')
                        callback();
                });
            }
        };

        // 開啟物料管理
        /*
        $scope.materialManagment = function(){
            is_force = false;
            $WatchDogService.stopWatch();
            $mdDialog.serviceDialog('F0101Service', {
                parent: 'E08',
                wo_no: ($scope.selectItem) ? $scope.selectItem.wo_no : '',
                op_no: $scope.stationMachine.op_no,
                machine_no: $scope.stationMachine.area_no,
                machine_no: $scope.stationMachine.machine_no,
                callback : function(){
                    if($scope.selectItem == undefined){
                        $WatchDogService.startWatch(dog);
                    } else {
                        focus_input_barcode();
                    }
                }
            });
        };
        */
        // 開啟物料批號綁定
        /*
        $scope.materialBinding= function(){
            is_force = false;
            $WatchDogService.stopWatch();
            $mdDialog.serviceDialog('E06Service', {
                stationMachine: angular.copy($scope.stationMachine),
                callback : function(dialog){
                    dialog.hide();
                    focus_input_barcode();
                }
            });
        };
        */

        var backStationMachine;
        $scope.setting = function(){
            is_force = false;
            document.getElementById('input_barcode').blur();
            // 20231127 add by shiwl	0151031: 作业站序号收集 初次进入 保存单笔确认，无法保存配置
            $scope.stationMachine.single_confirm = $scope.E08_single_confirm=='1'  ? false : true;
            backStationMachine = angular.copy($scope.stationMachine);
            //20181018 add by Dustdusk for M#:
            $scope.disconnection = false;
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            $WatchDogService.stopWatch();

            $mdDialog.serviceDialog('E08SettingsService', {
                parent: 'E08',
                stationMachine: angular.copy($scope.stationMachine),
                callback: function(dialog){
                    $scope.stationMachine = dialog.stationMachine;
                    applySetting(function(){
                        // 20231127 add by shiwl	0151031: 作业站序号收集 初次进入 保存单笔确认，无法保存配置
                        $scope.E08_single_confirm =  $scope.stationMachine.single_confirm  ? "0" : "1";
                        dialog.hide();
                    });
                },
                close: function(){
                    $scope.stationMachine = backStationMachine;
                    if($scope.selectItem == undefined){
                        $WatchDogService.startWatch(dog);
                    } else {
                        focus_input_barcode();
                    }
                }
            });
        };

        //人員上下工
        $scope.operatorList = function(){
            is_force = false;
            var stationMachine = $scope.stationMachine;
            stationMachine.parent = 'E08';
            stationMachine.pdline_no = $scope.stationMachine.machine_no;
            $mdDialog.serviceDialog('E02Service', {
                stationMachine: stationMachine,
                close:function(){
                    focus_input_barcode();
                },
                callback:function(callback){
                    stationLotInfoGet(callback, true);
                }
            });
        };

        //報廢原因開窗
        //待修改
        $scope.openAbnormalList = function(){
            is_force = false;
            $AbnormalService.init({
                plotInfo:{
                    plot_no:$scope.selectItem.plot_no,
                    op_no: $scope.stationMachine.op_no,
                    abnormal_detail:[]
                },
                limit_abnormal_type:[0],
                close:function(dialog){
                    dialog.hide();
                    focus_input_barcode();
                },
                confirm:function(dialog){
                    var scrap_detail = [], total_defect_qty = 0;
                    dialog.plotInfo.abnormal_detail.forEach(function(detail){
                        total_defect_qty += $calculater.decimalAdd(total_defect_qty, detail.defect_qty);
                        scrap_detail.push({
                            reason_type: detail.abnormal_type,
                            abnormal_no: detail.abnormal_no,
                            defect_qty: detail.defect_qty
                        });
                    });
                    if(total_defect_qty <= $scope.selectItem.remaining){
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.station_collect_scrap_process',
                            content: {
                                type: '1',
                                pdline_no : $scope.stationMachine.machine_no,
                                op_no : $scope.stationMachine.op_no,
                                plot_no : $scope.selectItem.plot_no,
                                scrap_detail:scrap_detail
                            },
                            success: function (data) {
                                $scope.$root.showToast($filter('translate')('E08.msg.defect_success'));
                                dialog.hide();
                                stationLotInfoGet(function(){
                                    //如果當下已經有選擇，檢查選擇的是否被出站
                                    if($scope.selectItem){
                                        var temp = $filter('filter')($scope.lot_result, {plot_no:$scope.selectItem.plot_no});
                                        if(!temp || temp.length == 0){
                                            $scope.selectItem = undefined;
                                            //當該筆已被清除，則判斷是否要載入第一筆 或是 開啟timer
                                            if($scope.lot_result.length > 0){
                                                clickItem($scope.lot_result[0]);
                                            } else {
                                                $WatchDogService.startWatch(dog);
                                            }
                                        } else {
                                            // 20240312 modify by Alan for M#0158582: 更新不良數量
                                            $scope.selectItem._total_defect_qty = $calculater.decimalAdd($scope.selectItem._total_defect_qty, total_defect_qty);
                                            updateRemaining();
                                        }
                                    }
                                }, true);
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('E08.msg.defect_qty_gt'));
                    }
                }
            });
        }

        $scope.confirm = function(){
            applySetting(function(){
                startSignalR();
            });
        };

        //載入工位機設定
        function applySetting(callback){
            //清除舊的資料
            //producttypeOpPositionSubopGet(function(){
                $scope.selectItem = undefined;
                $scope.lot_result = [];
                // 20190916 modify by Dstdusk for M#61062:增加帶回物料料批綁定相關資訊
                //$scope.$root.getService('E06Service', function($E06Service){
                //    $E06Service.LoadLotSet($scope.stationMachine, function(data){
                //        if(data && data.length > 0){
                //            if(!config.cache.permissions || config.cache.permissions.indexOf('E06')!=-1){
                //                $scope.stationMachine.showE06 = true;
                //            } else {
                //                $scope.stationMachine.showE06 = false;
                //            }
                //            for(var i = 0; i < data.length; i++){
                //                if(data[i].material_lotno == ''){
                //                    //請先確認工位機所綁定的物料批號!!
                //                    $scope.$root.showAlert($filter('translate')('E08.msg.confirm_MTL_lot_set'));
                //                    break;
                //                }
                //            }
                //        } else {
                //            $scope.stationMachine.showE06 = false;
                //        }
                        stationLotInfoGet(function(){
                            //20180529 modify by Dustdusk for M#45865:工位機增加標籤補印功能
                            $scope.stationMachine.print_sn = '0';
                            localStorage.setItem(config.appName + '_stationMachine_op', JSON.stringify($scope.stationMachine));
                            var id = $scope.stationMachine.area_no
                                    + $scope.stationMachine.op_no
                                    + $scope.stationMachine.machine_no;
                            ESOPSIze = JSON.parse(localStorage.getItem(config.appName + '_stationMachine_ESOPSize'));
                            if(ESOPSIze){
                                $scope.isESOPSize = ESOPSIze[id]||'';
                            } else {
                                ESOPSIze = {};
                            }
                            $scope.mode = '';
                            $scope.changeForm('E08_StationMachine');
                            if($scope.selectItem == undefined){
                                $WatchDogService.startWatch(dog);
                            }
                            if(callback)
                                callback();
                        }, true);
                //    });
                //});
            //});
        }

        $scope.clickItem = function(item){
            $scope.machine_panel_mode = undefined;
            var isSelected = false;
            if($scope.selectItem && $scope.selectItem.plot_no == item.plot_no){
                //當已選取，且該筆資料為自己時 則要走取消選取
                isSelected = true;
            }

            if(!isSelected){
                if($scope.selectItem && $scope.selectItem.plot_no != item.plot_no
                    && $scope.selectItem.pcs_detail && $scope.selectItem.pcs_detail.length > 0){
                    //當切換一筆的時候要提示
                    $scope.$root.showConfirm($filter('translate')('E08.msg.changeAlert'), function(dialog){
                        dialog.hide();
                        clickItem(item);
                    }, function(dialog){
                        dialog.hide();
                    });
                } else {
                    clickItem(item);
                }
            } else {
                if($scope.selectItem.pcs_detail && $scope.selectItem.pcs_detail.length > 0){
                    //當取消選取的時候要提示
                    $scope.$root.showConfirm($filter('translate')('E08.msg.cancelAlert'), function(dialog){
                        dialog.hide();
                        $scope.selectItem = undefined;
                        $WatchDogService.startWatch(dog);
                    }, function(dialog){
                        dialog.hide();
                    });
                } else {
                    $scope.selectItem = undefined;
                    $WatchDogService.startWatch(dog);
                }
            }
        };

        function clickItem(item, callback){
            stationWorkInfoGet(item, function (data) {
                // 20221121 modify by chenshibo for#122365：工位机剩余数量不会自动刷新
                if (data.curqty == undefined || data.curqty === null) {
                }
                else {
                    item.curqty = data.curqty;
                }
                if (data.inputqty == undefined || data.inputqty === null) {
                }
                else {
                    item.inputqty = data.inputqty;
                }
                $scope.selectItem = item;
                $scope.work_mode = $scope.selectItem.work_mode = data.work_mode;
                $scope.selectItem.total_pcs_qty_o = data.total_pcs_qty;//總計
                $scope.selectItem._total_defect_qty = 0; // 20240312 modify by Alan for M#0158582: 暫存報廢按鈕的數量
                //20190903 modify by Dustdusk for M#61511:調整input_qty取法
                $scope.selectItem.inputqty = $scope.selectItem.inputqty;
                $scope.selectItem.serial_rule = data.serial_rule;//編碼規則
                $scope.selectItem.esop_result = data.esop_result;//eSOP資訊
                $scope.selectItem.unit_result = data.unit_result;//部件欄位
                $scope.selectItem.pcs_detail = [];
                $scope.pageConfig.page = 0;
                //20181018 add by Dustdusk for M#:
                $scope.disconnection = false;
                if(refresh_timer != undefined){
                    $timeout.cancel(refresh_timer);
                    refresh_timer = undefined;
                }
                $WatchDogService.stopWatch();
                //PCS
                updateRemaining();
                //ESOP
                $scope.isListOpen = false;
                if($scope.selectItem.esop_result && $scope.selectItem.esop_result.length > 0){
                    $scope.clickEsopFile($scope.selectItem.esop_result[0]);
                } else {
                    $scope.clickEsopFile();
                }
                $timeout(function(){
                    // 20220329 modify by Alan for#109578 : 修正欄位寬度無法調整的問題
                    updatePCSList();
                    //20180529 modify by Dustdusk for M#45865:工位機增加標籤補印功能
                    $scope.stationMachine.print_sn = '0';
                    if($scope.selectItem.work_mode != 0){
                        focus_input_barcode();
                    }
                    if(callback)
                        callback();
                });
            });
        }

        $scope.pcs_remove = function(item){
            for(var index = 0; index < $scope.selectItem.pcs_detail.length; index++){
                if($scope.selectItem.pcs_detail[index].pcs_no == item.pcs_no){
                    $scope.selectItem.pcs_detail.splice(index, 1);
                    break;
                }
            }
            updateRemaining();
        };

        //20220614 modify wangzy M#0113042: [sMES]作業站序號收集出現資料庫執行時發生錯誤(宸曜)
        $scope.pcs_confirm = function (feedback) {
            var must_validate_unit_error_msg = check_need_validate_unit_detail();
            if ($scope.selectItem.unit_result.length > 0) {
                if (must_validate_unit_error_msg.length > 0) {
                    $scope.showAlert(must_validate_unit_error_msg.join("<br>"));
                    return;
                }
            }
            var pcs_detail = [];
            $scope.selectItem.pcs_detail.forEach(function(detail){
                if(!detail.saved){
                    pcs_detail.push(detail);
                }
            });
            if(pcs_detail.length > 0){
                stationCollectSnProcess_Imp(pcs_detail, function(){
                    stationProductQcProcess_Imp(pcs_detail, function(){
                        if(feedback){
                            feedback();
                        } else {
                            if($scope.selectItem){
                                var temp = $filter('filter')($scope.lot_result, {plot_no:$scope.selectItem.plot_no});
                                if(!temp || temp.length == 0){
                                    $scope.selectItem = undefined;
                                    //當該筆已被清除，則判斷是否要載入第一筆 或是 開啟timer
                                    if($scope.lot_result.length > 0){
                                        clickItem($scope.lot_result[0]);
                                    } else {
                                        $WatchDogService.startWatch(dog);
                                    }
                                } else {
                                    clickItem(temp[0]);
                                }
                            } else {
                                $WatchDogService.startWatch(dog);
                            }
                        }
                    }, focus_input_barcode);
                }, focus_input_barcode);
            } else {
                if(feedback)
                    feedback();
            }
        };

        function check_need_validate_unit_detail() {
            var SubOPMandatoryCollection = config.cache.sys_parameter.SubOPMandatoryCollection;
            var error_msg = [];
            //20211028 modify by chenshibo for#102217: 某产品类别并没有设置需要收集部件序号，只需要收集成品序号，但是却报错
            if ($scope.selectItem.unit_result.length > 0) {
                if ($scope.selectItem.pcs_detail.length > 0) {
                    $scope.selectItem.pcs_detail.forEach(function (detail) {
                        if (!detail.saved) {
                            if (SubOPMandatoryCollection && SubOPMandatoryCollection == "1") {
                                if (typeof detail.unit_detail === "undefined" || detail.unit_detail.length <= 0)
                                    error_msg.push($filter('translate')('E08.msg.must_need_unit_error_msg'));
                                detail.unit_detail.forEach(function (unitdetail) {
                                    if (typeof unitdetail.material_unit_no === "undefined" || unitdetail.material_unit_no == "") {
                                        var str_error = $filter('translate')('E01.product_sn') + detail.pcs_no + $filter('translate')('E01.unit_name') + unitdetail.unit_name + $filter('translate')('E01.msg.must_need_unit_error_msg2');
                                        error_msg.push(str_error);
                                    }
                                });
                            }
                        }
                    });
                }
            }
            return error_msg;
        }

        var is_force = true;
        $scope.barcodeScan = function(event){
            if(event != undefined && event.keyCode == 13){
                //20190408 modify by Dustdusk for M#56368: 修正工位機掃碼問題
                is_force = false;
                var input_barcode = event.target.value;
                event.target.value = '';
                document.getElementById('input_barcode').blur();
                if(input_barcode == '') {
                    is_force = true;
                    document.getElementById('input_barcode').focus();
                    document.getElementById('input_barcode').select();
                    notification('fail', $filter('translate')('E08.msg.barcode_empty'));
                } else if(input_barcode == 'PASS'){
                    $scope.pcs_confirm();
                } else if(input_barcode.indexOf('ERR@') == 0){
                    //下料
                    var _reason_no = input_barcode.replace('ERR@', '');
                    var pcs_detail = $scope.selectItem.pcs_detail[$scope.selectItem.pcs_detail.length-1];
                    if(!pcs_detail.badreason_detail){
                        pcs_detail.badreason_detail = [];
                    } else if(pcs_detail.badreason_detail.length>0){
                        var _temp = $filter('filter')(pcs_detail.badreason_detail, {reason_no:_reason_no});
                        if(_temp.length>0){
                            notification('fail', _reason_no + $filter('translate')('E07.msg.reason_duplicate'));
                            focus_input_barcode();
                            return;
                        }
                    }
                    $scope.$root.getService('E01badreasonService', function($E01badreasonService){
                        $E01badreasonService.GetReasonList({
                            op_no: $scope.stationMachine.op_no,
                            reason_no:_reason_no
                        }, function(itemList){
                            if(itemList.length>0){
                                var pcs_detail = $scope.selectItem.pcs_detail[$scope.selectItem.pcs_detail.length-1];
                                if(!pcs_detail.badreason_detail)
                                    pcs_detail.badreason_detail = [];
                                pcs_detail.badreason_detail.push({
                                    reason_no : itemList[0].page_no,
                                    reason_name : itemList[0].page_name
                                });
                                for(var i=0;i<pcs_detail.badreason_detail.length;i++){
                                    if(i==0){
                                        pcs_detail.badreason_desc = pcs_detail.badreason_detail[i].reason_name;
                                    } else {
                                        pcs_detail.badreason_desc += ', ' + pcs_detail.badreason_detail[i].reason_name;
                                    }
                                }
                            } else {
                                notification('fail', _reason_no + $filter('translate')('common.msg.no_data'));
                            }
                            focus_input_barcode();
                        });
                    });
                } else {
                    //20190408 modify by Dustdusk for M#56368: 修正工位機掃碼問題
                    var result = validateBarcode(input_barcode, $scope.selectItem.serial_rule, $scope.selectItem.unit_result.length>0);
                    if(result.msg==''){
                        if($scope.stationMachine.single_confirm){
                            if(result.type=='1'){
                                //成品
                                $scope.pcs_confirm(function(){
                                    //20190903 modify by Dustdusk for M#61511:收集的序號總數已等於目前生產批剩餘數量，請儲存後切換生產批
                                    if($scope.selectItem.remaining == 0){
                                        focus_input_barcode();
                                        notification('fail', $filter('translate')('E08.msg.Seq_count_complete'));
                                    } else {
                                        validate_pcs_detail(result.barcode, focus_input_barcode);
                                    }
                                });
                            } else if(result.type=='2'){
                                //部件
                                validate_unit_detail(result, focus_input_barcode);
                            }
                        } else {
                            if(result.type=='1'){
                                //20190903 modify by Dustdusk for M#61511:收集的序號總數已等於目前生產批剩餘數量，請儲存後切換生產批
                                if($scope.selectItem.remaining == 0){
                                    if($scope.selectItem.pcs_detail.length > 0){
                                        $scope.$root.showConfirm($filter('translate')('E08.msg.Seq_count_greate'), function(confirmDialog){
                                            confirmDialog.hide();
                                            $scope.pcs_confirm();
                                        } ,function(confirmDialog){
                                            confirmDialog.hide();
                                            focus_input_barcode();
                                        });
                                    } else {
                                        //判斷是否需要儲存
                                        focus_input_barcode();
                                        notification('fail', $filter('translate')('E08.msg.Seq_count_complete'));
                                    }
                                } else {
                                    // 20230428 modify by chenshibo for#134339: [sMES]H5-作業站序號收集無法輸入部件收集[智愛]
                                    var must_validate_unit_error_msg = check_need_validate_unit_detail();
                                    if (must_validate_unit_error_msg.length > 0) {
                                        $scope.showAlert(must_validate_unit_error_msg.join("<br>"));
                                        return;
                                    }
                                    validate_pcs_detail(result.barcode, focus_input_barcode);
                                }
                            } else if(result.type=='2'){
                                validate_unit_detail(result, focus_input_barcode);
                            }
                        }
                    } else {
                        if(result.isSHow){
                            $scope.$root.showAlert(result.msg);
                        } else {
                            notification('fail', result.msg);
                        }
                        focus_input_barcode();
                    }
                }
            } else if(window.cordova){
                //20180828 add by Dustdusk for Android 時不顯示小鍵盤
                if(event.key){
                    event.target.value += event.key;
                } else {
                    event.target.value += String.fromCharCode(event.keyCode);
                }
            }
        };

        $scope.input_blur = function(){
            // 20240411 modify by Alan for M#160065: 
            // 當聚焦在掃描輸入框以外的文字輸入框時，不觸發失焦事件
            // 並在失焦時，將光標聚焦在掃描輸入框
            $timeout(() => {
                const isFocusabledElem = document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA';
                if (document.activeElement.id != 'input_barcode' && isFocusabledElem) {
                    $(document.activeElement).one('blur', focus_window);
                    return
                }
                // 20230704 modify by wenwei for M#134315 根據掃描模式卡控，決定條碼序號的autofocus是否開啟
                if (is_force && config.setting.scanBarcod == 'Y') {
                    document.getElementById('input_barcode').focus();
                }
            })
        };

        /****Tools*************************************************************************************************************/
        var dog = {
            bark:function(feed, next){
                //使用user.infomation.get取得使用者資訊
                stationLotInfoGet(next, next == undefined);
            }
        };

        //根據傳入的serial_rule 檢查barcode
        function checkRule(barcode, serial_rule){
            var returnResult = {sucess_rule_base:[], msgStack: {}}, result = {};
            serial_rule.forEach(function(rule){
                //step 1. 初始化該序號種類的result
                if(!result[rule.serial_type]){
                    result[rule.serial_type] = {};
                }
                if(!result[rule.serial_type][rule.rule_base]){
                    result[rule.serial_type][rule.rule_base] = {};
                }
                if(!result[rule.serial_type][rule.rule_base][rule.rule_type]){
                    result[rule.serial_type][rule.rule_base][rule.rule_type] = {count:0, msg:[]};
                }

                //step 2. 統計該序號種類的數量
                result[rule.serial_type][rule.rule_base][rule.rule_type].count ++;

                //step 3. 開始檢核數量
                if(rule.rule_type == '1'){
                    //長度檢核
                    if((+rule.serial_length) != (+barcode.length)){
                        //輸入序號長度需為serial_length
                        result[rule.serial_type][rule.rule_base][rule.rule_type].msg.push($filter('translate')('E08.msg.seq_length')+rule.serial_length);
                    }
                } else if(rule.rule_type == '2'){
                    //是否包含contain_string
                    if((barcode.indexOf(rule.contain_string)+1) != (+rule.start_index)){
                        //輸入序號位置start_index需為contain_string
                        result[rule.serial_type][rule.rule_base][rule.rule_type].msg.push(
                            $filter('translate')('E08.msg.contain_string_1')+rule.start_index+
                            $filter('translate')('E08.msg.contain_string_2')+rule.contain_string);
                    }
                } else if(rule.rule_type == '3'){
                    //輸入序號起始需為first_string
                    if(barcode.indexOf(rule.first_string) != 0){
                        result[rule.serial_type][rule.rule_base][rule.rule_type].msg.push($filter('translate')('E08.msg.first_string')+rule.first_string);
                    }
                } else if(rule.rule_type == '4'){
                    //輸入序號結尾需為last_string
                    var index = barcode.lastIndexOf(rule.last_string);
                    if((index+rule.last_string.length) != barcode.length){
                        result[rule.serial_type][rule.rule_base][rule.rule_type].msg.push($filter('translate')('E08.msg.last_string')+rule.last_string);
                    }
                }else if(rule.rule_type == '5'){
                    //20190826 modify by Dustdusk for M#61058: 增加包含特定字元的選項
                    //輸入序號包含contain_string
                    if(barcode.lastIndexOf(rule.contain_string) == -1){
                        result[rule.serial_type][rule.rule_base][rule.rule_type].msg.push($filter('translate')('E08.msg.contain_string')+rule.contain_string);
                    }
                }
            });
            for(var serial_type in result){
                returnResult.msgStack[serial_type] = [];
                returnResult.sucess_rule_base[serial_type] = [];
                for(var rule_base in result[serial_type]){
                    var count = 0;
                    var total_count = 0;
                    for(var rule_type in result[serial_type][rule_base]){
                        total_count++;
                        var type_result = result[serial_type][rule_base][rule_type];
                        if(type_result.count == type_result.msg.length){
                            //表示每個檢核都沒通過
                            if(returnResult.sucess_rule_base[serial_type].length == 0)
                                returnResult.msgStack[serial_type] = returnResult.msgStack[serial_type].concat(type_result.msg);
                        } else {
                            count ++;
                        }
                    }
                    //表示該rule_base 所有的檢查條件都通過
                    if(count == total_count){
                        returnResult.sucess_rule_base[serial_type].push(rule_base);
                        returnResult.msgStack[serial_type] = [];
                    }
                }
            }

            return returnResult;
        }

        /**
         *  needUnit 表示是否需要部件序號
        **/
        function validateBarcode(barcode, serial_rule, needUnit){
            var returnResult, result = {barcode:barcode, msg:'', isShow:false};

            //20190826 modify by Dustdusk for M#61058: 可不用設定序號規則
            returnResult = checkRule(barcode, serial_rule);
            var msgStack = returnResult.msgStack;

            if(!needUnit){
                //不需部件序號、表示此序號為成品序號
                if(msgStack['1'] == undefined || msgStack['1'].length == 0){
                    result.type = 1;
                } else {
                    result.isShow = true;
                    //成品序號請符合以下:
                    result.msg += $filter('translate')('E08.msg.PCS_valilogic')+'<br>';
                    msgStack['1'].forEach(function(errorMsg){
                        result.msg += errorMsg + '<br>';
                    });
                }
            } else {
                //20191121 modify by Dustudsk for M#64618: 修正產品設定、物料沒設定時判斷錯誤
                if(msgStack['1'] == undefined || msgStack['1'].length == 0){
                    // 沒有設定成品，所以也不用管部件序號，按照順序填
                    var pcs_detail = $scope.selectItem.pcs_detail[$scope.selectItem.pcs_detail.length-1];
                    if(pcs_detail == undefined){
                    	//已刷滿部件序號，要接著刷成品序號
                        result.type = 1;
                    } else {
                        var _empty_unit = pcs_detail.unit_detail.find(function(detail){return detail.material_unit_no == undefined});
                        if(_empty_unit == undefined){
                            //已刷滿部件序號，要接著刷成品序號
                            result.type = 1;
                        } else {
                            //繼續刷部件
                            if(msgStack['2'] && msgStack['2'].length > 0){
                                result.type = 1;
                            } else {
                                result.type = 2;
                                result.sucess_rule_base = returnResult.sucess_rule_base[result.type]||[];
                            }
                        }
                    }
                } else {
                    if(!msgStack['2'])
                        msgStack['2'] = [];

                    if(msgStack['1'].length == 0 && msgStack['2'].length == 0){
                        //表示通過成品序號檢核及部件序號檢核
                        result.isShow = true;
                        result.msg = $filter('translate')('E08.msg.duplicate_valilogic') + '<br>';
                    } else if(msgStack['1'].length == 0 && msgStack['2'].length > 0){
                        //成品序號檢驗成功、部件序號檢驗失敗
                        result.type = 1;
                    } else if(msgStack['1'].length > 0 && msgStack['2'].length == 0){
                        //成品序號檢驗失敗、部件序號檢驗成功
                        result.type = 2;
                        result.sucess_rule_base = returnResult.sucess_rule_base[result.type]||[];
                    } else if(msgStack['1'].length > 0 && msgStack['2'].length > 0){
                        //成品序號檢驗失敗、部件序號檢驗失敗
                        //序號檢核錯誤.
                        result.msg += $filter('translate')('E08.msg.Seq_valilogic')+'<br>';
                        //成品序號請符合以下:
                        result.msg += $filter('translate')('E08.msg.PCS_valilogic')+'<br>';
                        msgStack['1'].forEach(function(errorMsg){
                            result.msg += errorMsg + '<br>';
                        });
                        //部件序號請符合以下:
                        result.msg += $filter('translate')('E08.msg.Unit_valilogic')+'<br>';
                        msgStack['2'].forEach(function(errorMsg){
                            result.msg += errorMsg + '<br>';
                        });
                    }
                }
            }
            return result;
        }

        function validate_pcs_detail(input_barcode, feedback){
            if($scope.stationMachine.validate_mode == 0){
                station_collect_sn_check_process({
                    pcs_detail:[{pcs_no:input_barcode}],
                    feedback:function(){
                        addPCS_detail(input_barcode, feedback);
                    },
                    errorback:feedback
                });
            } else {
                addPCS_detail(input_barcode, feedback);
            }
        }
        function validatePCS(input_barcode){
            for(var i = 0;i<$scope.selectItem.pcs_detail.length;i++){
                if(input_barcode == $scope.selectItem.pcs_detail[i].pcs_no){
                    //成品序號重複
                    return input_barcode + $filter('translate')('E08.msg.PCSSeq_duplicate');
                }
            }
            return '';
        }

        function addPCS_detail(barcode, feedback){
            var msg = validatePCS(barcode);
            if(msg == ''){
                var pcs_detail = {pcs_no:barcode, unit_detail : [], insert_time:Date.now(), saved:false};
                $scope.selectItem.unit_result.forEach(function(detail){
                    pcs_detail.unit_detail.push(angular.extend({},detail));
                });
                $scope.selectItem.pcs_detail.push(pcs_detail);
                updateRemaining();

                notification('success');
                //20190903 modify by Dustdusk for M#61511:
                if(ValidateFull()){
                    //部件序號已刷滿，提示[收集的序號總數已經大於目前生產批數量]
                    $scope.$root.showConfirm($filter('translate')('E08.msg.Seq_count_greate'), function(confirmDialog){
                        confirmDialog.hide();
                        $scope.pcs_confirm();
                    } ,function(confirmDialog){
                        confirmDialog.hide();
                        if(feedback)
                            feedback();
                    });
                }else if(feedback){
                    feedback();
                }
            } else {
                notification('fail', msg);
                if(feedback){
                    feedback();
                }
            }
        }

        //20200515 modify by Dustdusk for M#: 先本地端檢查是否重複
        function validateUnit(input_barcode){
            for(var i = 0; i < $scope.selectItem.pcs_detail.length-1; i++){
                for(var j = 0; j < $scope.selectItem.pcs_detail[i].unit_detail.length; j++){
                    if($scope.selectItem.pcs_detail[i].unit_detail[j].material_unit_no == input_barcode){
                        return input_barcode + $filter('translate')('E08.msg.UNITSeq_duplicate');
                    }
                }
            }
            return '';
        }

        function validate_unit_detail(result, feedback){
            //20200515 modify by Dustdusk for M#: 先本地端檢查
            var _msg = validateUnit(result.barcode);
            if(_msg == ''){
                if($scope.stationMachine.validate_mode == 0){
                    station_collect_sn_check_process({
                        unit_item:{material_unit_no:result.barcode},
                        feedback:function(){
                            addunit_detail(result, feedback);
                        },
                        errorback:feedback
                    });
                } else {
                    addunit_detail(result, feedback);
                }
            } else {
                notification('fail', _msg);
                if(feedback){
                    feedback();
                }
            }
        }

        //寫入部件序號
        function addunit_detail(result, feedback){
            if($scope.selectItem.pcs_detail.length>0){
                var isFull = 0, isFind = false;
                var pcs_detail = $scope.selectItem.pcs_detail[$scope.selectItem.pcs_detail.length-1];
                //回填部件序號的時候，根據序號的物料種類進行填入
                for(var i = 0; i < pcs_detail.unit_detail.length;i++){
                    var detail = pcs_detail.unit_detail[i];
                    if(result.sucess_rule_base.length == 0){
                        if(detail.material_unit_no == undefined){
                            detail.material_unit_no = result.barcode;
                            isFind = true;
                            isFull++;
                            break;
                        }
                    } else {
                        for(var j = 0; j < result.sucess_rule_base.length;j++){
                            if(detail.material_type == result.sucess_rule_base[j]){
                                if(!detail.material_unit_no){//沒找到，則填入
                                    detail.material_unit_no = result.barcode;
                                    isFind = true;
                                    break;
                                } else if(detail.material_unit_no == result.barcode){
                                    detail.material_unit_no = undefined;
                                    isFind = true;
                                    break;
                                }
                            }
                        }
                        //表示有刷過
                        if(detail.material_unit_no != undefined)
                            isFull++

                        //20191121 modify by Dustdusk for M#64618: 修正相同物料規則時會同時填到兩個內
                        if(isFind)
                            break;
                    }
                }
                if(pcs_detail.unit_detail.length <= isFull){
                    if(!isFind){
                        //部件序號已刷滿
                        notification('fail', $filter('translate')('E08.msg.Unit_seq_full'));
                    } else if($scope.selectItem.remaining == 0) {
                        notification('success');
                        //部件序號已刷滿，提示[收集的序號總數已經大於目前生產批數量]
                        $scope.$root.showConfirm($filter('translate')('E08.msg.Seq_count_greate'), function(confirmDialog){
                            confirmDialog.hide();
                            $scope.pcs_confirm();
                        } ,function(confirmDialog){
                            confirmDialog.hide();
                            if(typeof(feedback) == 'function')
                                feedback();
                        });
                    } else if(typeof(feedback) == 'function'){
                        notification('success');
                        feedback();
                    }
                } else if(feedback){
                    notification('success');
                    feedback();
                }
            } else {
                //請先刷入成品序號.
                notification('fail', $filter('translate')('E08.msg.PCS_seq_first'));
                if(feedback){
                    feedback();
                }
            }
        }

        //判斷部件序號是否刷滿
        function ValidateFull(){
            if($scope.selectItem.remaining == 0){
                if($scope.selectItem.work_mode == 2){
                    //刷成品序號 + 部件序號
                    var pcs_detail = $scope.selectItem.pcs_detail[$scope.selectItem.pcs_detail.length-1];
                    if(pcs_detail.unit_detail && pcs_detail.unit_detail.length > 0){
                        for(var i = 0; i < pcs_detail.unit_detail.length;i++){
                            if(pcs_detail.unit_detail[i].material_unit_no == undefined){
                                //表示尚未刷滿
                                return false;
                            }
                        }
                    }
                }
                return true;
            } else {
                return false;
            }
        }

        //計算剩餘
        function updateRemaining(){
            $scope.selectItem.total_pcs_qty = (+$scope.selectItem.total_pcs_qty_o) + (+$scope.selectItem.pcs_detail.length);
            // 20240312 modify by Alan for M#0158582: 報廢按鈕送出之後不會重新取得inputqty，所以這裡要扣掉報廢按鈕的數量
            $scope.selectItem.remaining = (+$scope.selectItem.inputqty) - (+$scope.selectItem.total_pcs_qty) - ($scope.selectItem._total_defect_qty); 
            if($scope.selectItem.remaining<0){
                $scope.selectItem.remaining = 0;
            }
        }

        function focus_input_barcode(){
            is_force = true;
            document.getElementById('input_barcode').focus();
            // 20230523 關閉select()避免已刷入的條碼被清除
            // document.getElementById('input_barcode').select();
        }

        function focus_window() {
            if(is_force){
                setTimeout(function(){
                    $(window).focus();
                    focus_input_barcode();
                },200);
            }
        }

        function notification(type, msg){
            var level = '';
            if(type == 'success'){
                var successSound = document.getElementById('success-sound');
                successSound.play();
            } else if(type == 'fail'){
                var failSound = document.getElementById('fail-sound');
                failSound.play();
                level = 'error';
            }
            if(msg){
                $scope.$root.showToast(msg, level);
            }
        }
        /****連接後台***********************************************************************************************************/
        //取得工序資訊
        /*
        function producttypeOpPositionSubopGet(feedback){
            var content = {
                area_no : $scope.stationMachine.areano,
                op_no : $scope.stationMachine.op_no,
                machine_no : $scope.stationMachine.machine_no
            };

            $MMWService.sendToServer({
               uri : 'ServicesSTD.Module_SN.producttype_op_position_subop_get',
                content: content,
                success: function (data) {
                    $scope.isSPCMode = (data.qc_test == 1); //成品序號是否要顯示「是否送驗」欄位: 0=否, 1=是
                    if(feedback)
                        feedback();
                }
            });
        }
        */

        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            $scope.$root.showAlert(msg);
            if(!isShowLoading){
                $scope.disconnection = true;
                $scope.refresh =  function(){
                    $scope.disconnection = false;
                    $timeout.cancel(refresh_timer);
                    refresh_timer = undefined;
                    callback();
                };
                if(refresh_timer == undefined){
                    refresh_timer = $timeout(function(){
                        $scope.refresh();
                    }, config.setting.RefreshTime*1000);
                }
            }
        }

        //取得目前作業站上Running生產批
        function stationLotInfoGet(feedback, isShowLoading){
            var content = {
                type:'1',
                area_no : $scope.stationMachine.area_no,
                op_no : $scope.stationMachine.op_no,
                machine_no : $scope.stationMachine.machine_no,
                status : '1'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.station_lot_info_get',
                content: content,
                success: function (data) {
                    var selectItem;
                    //20190708 modify by Dustdusk for M#59502: 沒有工序的情況下有可能引發後面的錯誤
                    if(data.lot_result == undefined || data.lot_result===null){
                        $scope.lot_result = [];
                    } else {
                        if($scope.lot_result == undefined || $scope.lot_result === null || $scope.lot_result.length == 0){
                            if(data.lot_result.length > 0){
                                selectItem = data.lot_result[0];
                            }
                        }
                        $scope.lot_result = data.lot_result;
                    }
                    $scope.stationMachine.employee_work_detail = data.employee_work_detail;
                    if(selectItem){
                        clickItem(selectItem, feedback);
                    } else  if(feedback){
                        feedback();
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        stationLotInfoGet(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        stationLotInfoGet(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //透過生產批取得作業資訊 & 序號規則設定
        function stationWorkInfoGet(item, feedback){
            var content = {
                type:'1',
                area_no : $scope.stationMachine.area_no,
                op_no : $scope.stationMachine.op_no,
                machine_no : $scope.stationMachine.machine_no,
                plot_no : item.plot_no
            };

            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SN.station_work_info_get',
                content: content,
                success: function (data) {
                    if(feedback)
                            feedback(data);
                },
                error: function(data){
                    $scope.$root.showAlert(data.Message, {error_detail:data});
                    $scope.selectItem = undefined;
                }
            });
        }

        function stationCollectSnProcess_Imp(pcs_detail, feedback, errorback){
            stationCollectSnProcess(pcs_detail, function(){
                $scope.selectItem.pcs_detail.forEach(function(detail){
                    if(!detail.saved){
                        detail.saved = true;
                    }
                });
                if(feedback)
                    feedback();
            }, function(){
                if(errorback)
                    errorback();
            });
        }

        //序號收集作業
        function stationCollectSnProcess(pcs_detail, feedback, errorback){
            var content = {
                type: '1',
                area_no : $scope.stationMachine.area_no,
                op_no : $scope.stationMachine.op_no,
                machine_no : $scope.stationMachine.machine_no,
                plot_no : $scope.selectItem.plot_no,
                validate_mode:$scope.stationMachine.validate_mode,
                work_mode : $scope.selectItem.work_mode,
                //20180206 modify by Dustdusk for M#43957:一个产品可以绑定多个标签类别，并打印多个标签
                label_no:$scope.selectItem.label_no,
                //20180529 modify by Dustdusk for M#45865:工位機增加標籤補印功能
                print_sn:$scope.stationMachine.print_sn,
                pcs_detail:pcs_detail
            };

            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SN.station_collect_sn_process',
                content: content,
                success: function (data) {
                    printTag(0, data.pcsno_detail);
                    if(feedback){
                        feedback();
                    }
                },
                error: function(data){
                    $scope.$root.showAlert(data.Message, {error_detail:data});
                    if(errorback){
                        errorback();
                    }
                }
            });
        }

        function printTag(index, pcsno_detail){
            if(pcsno_detail && index < pcsno_detail.length){
                if(window.nodeRequire){
                    var exec = window.nodeRequire('child_process').exec;
                    exec(pcsno_detail[index].commandline, function(error, stdout, stderr){
                        if(error){
                            console.error(error);
                            $scope.$root.showToast($filter('translate')('E08.msg.cantprint'));
                        }

                        index = index +1;
                        printTag(index, pcsno_detail);
                    });
                }
            }
        }

        function stationProductQcProcess_Imp(pcs_detail, feedback, errorback){
            if($scope.isSPCMode){
                stationProductQcProcess(pcs_detail, function(){
                    $scope.selectItem.pcs_detail.forEach(function(detail){
                        if(!detail.is_spc_checked){
                            detail.is_spc_checked = true;
                        }
                    });
                    if(feedback)
                        feedback();
                }, function(){
                    if(errorback)
                        errorback();
                });
            } else {
                if(feedback)
                    feedback();
            }
        }

        //工位機成品送作驗作業
        function stationProductQcProcess(pcs_detail, feedback, errorback){
            var content = {
                area_no : $scope.stationMachine.area_no,
                op_no : $scope.stationMachine.op_no,
                machine_no : $scope.stationMachine.machine_no,
                plot_no : $scope.selectItem.plot_no,
                qty: $scope.selectItem.curqty,
                pcs_detail:pcs_detail
            };
            $MMWService.sendToSMESServer({
                uri: 'tcSMES.clsStation.station_product_qc_process',
                content: content,
                success: function (data) {
                    if(feedback){
                        feedback(data);
                    }
                },
                error: function(data){
                    $scope.$root.showAlert(data.Exception, function(){
                        if(errorback){
                            errorback();
                        }
                    });
                }
            });
        }

        /****ESOP********************************************************************************************************/
        $scope.clickEsopFile = function(esopItem){
            if(esopItem){
                $scope.currentFile = {esop_content:esopItem.esop_content, content_type : esopItem.content_type};
                if($scope.currentFile.esop_content.indexOf('http://') == -1){
                    $scope.currentFile.esop_content = 'http://'+config.server.ip+':'+ config.server.port + $scope.currentFile.esop_content;
                }

                if($scope.currentFile.content_type == '0'){
                    //PDF
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+$scope.currentFile.esop_content
                        +'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                        
                    // 20220315 modify by Alan for M#106738: 使用外部程式開啟PDF檔案內的連結
                    // 20220408 modify by Alan for M#106738: 修正連結開啟異常
                    var pdfElem = document.getElementById('kmi-pdf-panel');

                    pdfElem.addEventListener('load', function() {
                        var pdfFrame = window.frames['kmi-pdf-panel']
                        pdfFrame.PDFViewerApplication.preferences.set('externalLinkTarget', 2);
                        
                        if (!shell) return
                        pdfFrame.document.addEventListener('pagerendered', function() {
                            var links = this.querySelectorAll('.linkAnnotation a[href]');
                            links.forEach(function(link) {
                                if (link.getAttribute('listener') === 'true') return

                                link.setAttribute('listener', 'true');
                                link.addEventListener('click', function(e) {
                                    e.preventDefault();
                                    var href = e.target.getAttribute('href');
                                    var isExternalLink = externalLinkPrefixList.find((prefix) => href.startsWith(prefix));
                                    if (isExternalLink) {
                                        shell.openExternal(e.target.href);
                                    }
                                })
                            })
                        });
                    })
                } else if($scope.currentFile.content_type == '1'){
                    //影片
                    var VideoPanel = document.getElementById('kmi-video-panel');
                    VideoPanel.innerHTML = '';
                    VideoPanel.innerHTML = '<source src="'+$scope.currentFile.esop_content+'" type="video/mp4">';
                    //VideoPanel.innerHTML = '<source src='http://gallery.mjes.ntpc.edu.tw/moodle/pluginfile.php/15477/mod_resource/content/3/4%E6%98%9F%E6%98%9F%E4%B8%80%E5%A4%A9%E7%9A%84%E9%81%8B%E8%A1%8C%20%281%29.mp4' type=\'video/mp4\'>';
                    // 20200727 modify by WeiTing for M#75510: ESOP切換影片時，需要重新 load，不然會無法切換。
                    VideoPanel.load();
                } else if($scope.currentFile.content_type == '2'){
                    //圖片
                    var kmiImgPanel = document.getElementById('kmi-img-panel');
                    kmiImgPanel.style.width = '100%';
                    kmiImgPanel.style.height = '100%';
                }
            } else {
                $scope.currentFile = esopItem;
                document.getElementById('kmi-pdf-panel').src = '';
                document.getElementById('kmi-video-panel').innerHTML = '';
            }
        };
        $scope.zoom_in = function(){
            if($scope.currentFile.content_type == '0'){
                window.frames['kmi-pdf-panel'].zoom_in();
            } else if($scope.currentFile.content_type == '2'){
                var kmiImgPanel = document.getElementById('kmi-img-panel');
                kmiImgPanel.style.width = kmiImgPanel.width*1.1 + 'px';
                kmiImgPanel.style.height = kmiImgPanel.height*1.1 + 'px';
            }
        },
        $scope.zoom_out = function(){
            if($scope.currentFile.content_type == '0'){
                window.frames['kmi-pdf-panel'].zoom_out();
            } else if($scope.currentFile.content_type == '2'){
                var kmiImgPanel = document.getElementById('kmi-img-panel');
                kmiImgPanel.style.width = kmiImgPanel.width*0.9 + 'px';
                kmiImgPanel.style.height = kmiImgPanel.height*0.9 + 'px';
            }
        };
        $scope.changeESOPSize = function(size_type){
            if($scope.isESOPSize != size_type)
                $scope.isESOPSize = size_type;
            else
                $scope.isESOPSize = '';

            var id = $scope.stationMachine.area_no
            + $scope.stationMachine.op_no
            + $scope.stationMachine.machine_no;
            ESOPSIze[id] = $scope.isESOPSize;
            localStorage.setItem(config.appName + '_stationMachine_ESOPSize', JSON.stringify(ESOPSIze));
            $timeout(function(){
                var input_barcode = document.getElementById('input_barcode');
                if($scope.selectItem.work_mode != 0 && input_barcode){
                    input_barcode.focus();
                }
            });
        };
        $scope.changePanelSize = function(size_type){
            if($scope.machine_panel_mode == undefined){
                $scope.machine_panel_mode = size_type;
            } else {
                $scope.machine_panel_mode = undefined;
            }
        }

        //20170206 modify by Dustdusk modify for M0043957#:
        $scope.selectLabel = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 25,
                key:'page_no',
                selectCode:$scope.selectItem.label_no,
                beforeShown:function(){
                    is_force = false;
                },
                back:function(hide){
                    hide();
                    focus_input_barcode();
                },
                header: [
                    {label: $filter('translate')('E08.label_type'), code:'page_name'},
                    {label: $filter('translate')('E08.label_no'), code:'page_no'}
                ],
                confirm : function(selectItem){
                    $scope.selectItem.label_no = selectItem.page_no;
                    focus_input_barcode();
                }
            });
        };

        function startSignalR(callback){
            if(!chatHub){
                chatHub = $MMWService.createHub('chatHub', {connected:callback,listeners:{
                    "broadcastMessage":function(method, content) {
                        //console.log(method);
                        if(method == 'station_checkin_esopfile' || method == 'station_checkout_esopfile'){
                            content = JSON.parse(content);
                            if($scope.stationMachine.op_no == content.op_no){
                                stationLotInfoGet(function(){
                                    //如果當下已經有選擇，檢查選擇的是否被出站
                                    if($scope.selectItem){
                                        var temp = $filter('filter')($scope.lot_result, {plot_no:$scope.selectItem.plot_no});
                                        if(!temp || temp.length == 0){
                                            $scope.selectItem = undefined;
                                            //當該筆已被清除，則判斷是否要載入第一筆 或是 開啟timer
                                            if($scope.lot_result.length > 0){
                                                clickItem($scope.lot_result[0]);
                                            } else {
                                                $WatchDogService.startWatch(dog);
                                            }
                                        }
                                    } else {
                                        if($scope.lot_result.length > 0){
                                            var temp = $filter('filter')($scope.lot_result, {plot_no:content.plot_no});
                                            if(temp && temp.length>0){
                                                clickItem(temp[0]);
                                            } else {
                                                clickItem($scope.lot_result[0]);
                                            }
                                        }
                                    }
                                }, false);
                            };
                        }
                    }
                }});
            } else {
                if(callback)
                    callback();
            }
        }

        function stopSignalR(callback){
            if(chatHub && chatHub){
                chatHub.disconnect();
                chatHub = undefined;
            }
            if(callback)
                callback();
        }

        $scope.changePrint_sn = function(){
            if($scope.stationMachine.print_sn == '1'){
                $scope.stationMachine.print_sn = '0';
            } else {
                $scope.stationMachine.print_sn = '1';
            }
        };

        // 設定 ==========================================================
        //生產線開窗
        $scope.loadArea = function(){
            $scope.$root.getService('E08SettingsService', function($E08SettingsService){
                $E08SettingsService.loadArea($scope.stationMachine, function(data){
                    $scope.stationMachine = data;
                    $scope.loadOp();
                });
            });
        };
        //作業站
        $scope.loadOp = function(){
            $scope.$root.getService('E08SettingsService', function($E08SettingsService){
                $E08SettingsService.loadOP($scope.stationMachine, function(data){
                    $scope.stationMachine = data;
                    $scope.loadMachine();
                });
            });
        };
        //工位
        $scope.loadMachine = function(){
            $scope.$root.getService('E08SettingsService', function($E08SettingsService){
                $E08SettingsService.loadMachine($scope.stationMachine, function(data){
                    $scope.stationMachine = data;
                });
            });
        };
        // 設定 ==========================================================

        // 設備點檢
        //20181015 modify by Dustdusk for M#51359:
        $scope.load_B0210 = function(){
            is_force = false;
            var options = {
                machine_no:$scope.stationMachine.machine_no,
                machine_display:$scope.stationMachine.machine_no + '('+$scope.stationMachine.machine_name+')',
                back : function(){
                    focus_input_barcode();
                }
            };
            $mdDialog.serviceDialog('B0210Service', options, options.back);
        };

        $scope.gotoE05 = function(){
            $scope.$root.getService('E08SettingsService', function($E08SettingsService){
                $E08SettingsService.gotoE05($scope.stationMachine);
            });
        }

        // 不良原因選擇
        $scope.loadBadReason = function(item){
            is_force = false;
            $mdDialog.serviceDialog('E01badreasonService',{
                op_no: $scope.stationMachine.op_no,
                itemList:item.badreason_detail||[],
                callback:function(dialog){
                    //20200602 modify by dustdusk for M#71031: 修正刪除後顯示內容沒有同步刪除
                    item.badreason_desc = '';
                    item.badreason_detail = dialog.itemList;
                    for(var i=0;i<item.badreason_detail.length;i++){
                        if(i==0){
                            item.badreason_desc = item.badreason_detail[i].reason_name;
                        } else {
                            item.badreason_desc += ', ' + item.badreason_detail[i].reason_name;
                        }
                    }
                    focus_input_barcode();
                    dialog.hide();
                },
                close:function(){
                    focus_input_barcode();
                }
            });
        }

        function station_collect_sn_check_process(content){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.station_collect_sn_check_process',
                content: {
                    type:'1',
                    area_no : $scope.stationMachine.area_no,
                    op_no : $scope.stationMachine.op_no,
                    machine_no : $scope.stationMachine.machine_no,
                    plot_no : $scope.selectItem.plot_no,
                    pcs_detail:content.pcs_detail,
                    unit_item:content.unit_item
                },
                success: function (data) {
                    if(content.feedback){
                        content.feedback();
                    }
                },
                error: function(data){
                    $scope.$root.showAlert(data.Message, {error_detail:data});
                    if(content.errorback){
                        content.errorback();
                    }
                }
            });
        }

        // 20201127 add FOR #81457
        var dialogList = [
            //自检
            {
                name: $filter('translate')('B0240.menuTitle'), status: [], programName: 'B0243',
                init: function () {
                    $mdDialog.serviceDialog('B0243Service', {
                        plotItem: $scope.plotItem,
                        machine_no: $scope.stationMachine.machine_no,
                        area_no: '',
                        type: '5',
                        parent:"E08",
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id: $scope.selectItem.item_no,
                        feedback: function () {
                            dog.bark();
                            focus_input_barcode();
                        }
                    });
                }
            },
            //首件檢查
            {
                name: $filter('translate')('B0207.menuTitle_0'), status: [], programName: 'B0242-1',
                init : function(){
                    $mdDialog.serviceDialog('B0242Service', {
                        plotItem:$scope.plotItem,
                        machine_no: $scope.stationMachine.machine_no,
                        area_no:'',
                        type: '0',
                        parent:"E08",
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id:$scope.selectItem.item_no,
                        feedback:function(){
                            dog.bark();
                            focus_input_barcode();
                        }
                    });
                }},
            //巡檢
            {
                name: $filter('translate')('B0207.menuTitle_2'), status: [], programName: 'B0242-2',
                init : function(){
                    $mdDialog.serviceDialog('B0242Service', {
                        plotItem:$scope.plotItem,
                        machine_no:$scope.stationMachine.machine_no,
                        area_no:'',
                        type: '2',
                        parent:"E08",
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id:$scope.selectItem.item_no,
                        feedback:function(){
                            dog.bark();
                            focus_input_barcode();
                        }
                    });
                }
            },
            //末检
            {
                name: $filter('translate')('B0241.menuTitle'), status: [], programName: 'B0244',
                init: function () {
                    $mdDialog.serviceDialog('B0244Service', {
                        plotItem: $scope.plotItem,
                        machine_no:  $scope.stationMachine.machine_no,
                        area_no: '',
                        type: '4',
                        parent:"E08",
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號��?
                        product_id: $scope.selectItem.item_no,
                        feedback: function () {
                            dog.bark();
                            focus_input_barcode();
                        }
                    });
                }
            },
            {name: $filter('translate')('B0201.X'), status: [], programName : ''}
        ];

        $scope.openToolBar=function (status) {
            $scope.workLogStatus = status;
            $mdDialog.dialog(
                'module/moduleB/program/B02/B0201/ToolBar.tmp.html',
                ToolBarController
            );
        };

        function ToolBarController(dialog) {
            return {
                dialogList: dialogList,
                buttonAction:function(button){
                    this.hide();
                    is_force = false;
                    if(button.init)
                        button.init($scope.workLogStatus);
                },
                btnFilter:function(button){
                    if(!config.cache.permissions || config.cache.permissions.indexOf(button.programName)!=-1 || !button.programName){
                        return button;
                    }
                },
                background:{
                    class:['toolbar-background'],
                    click: function(){
                        dialog.hide();
                        focus_input_barcode()
                    }
                }
            };
        }

        $scope.selectCheck = function (item) {
            if(item.pcs_no){
                $scope.plotItem.op_no = $scope.stationMachine.op_no,
                $scope.plotItem.plot_no = $scope.selectItem.plot_no,
                $scope.plotItem.pcs_no = item.pcs_no
                $scope.plotItem.station_no = $scope.stationMachine.machine_no
                $scope.openToolBar(0)
            }
        }

        // 20220329 modify by Alan for#109578 : 修正欄位寬度無法調整的問題
        // 更新部件清單
        function updatePCSList() {
            let list = genaratePCSList();
            if ($('.kmi-list.pcs-list').length != 0) {
                $('.kmi-list.pcs-list').replaceWith(list);
            } else {
                $(list).insertAfter('.fields.info');
            }
            $compile(list)($scope);
        }

        function genaratePCSList() {
            let rows = generateRow();
            let start = `
                <div class="kmi-list pcs-list" ng-hide="isShowProductionInfo"  kmi-scrollbar="600px">
                    <div class="kmi-list__header">
                        <div class="kmi-list__column" style="flex:0 0 100px;z-index:1;position: relative;" ng-bind="'E01.is_spc_checked' | translate" ng-show="isSPCMode"></div>
                        <div class="kmi-list__column" style="flex: 0 0 40px;"></div>
                        <div class="kmi-list__column" style="flex: 0 0 100px;" ng-bind="'E01.product_sn' | translate"></div>`;
            let end = `
                        <div class="kmi-list__column" style="flex: 0 0 100px;" ng-bind="'E01.badreason' | translate"></div>
                    </div>
                    <div class="kmi-list__row-content">${rows}</div>
                    <div class="page-content">
                        <div class="page-icon">
                            <img src="image/icons/dropleft.png" />
                            <div class="kmi-can-click" ng-click="pageConfig.page = (pageConfig.page-1<0?0:pageConfig.page-1);"></div>
                        </div>
                        <label ng-bind="(pageConfig.page +1)+' / '+pageConfig.total_page"></label>
                        <div class="page-icon">
                            <img src="image/icons/dropright.png" />
                            <div class="kmi-can-click" ng-click="pageConfig.page = (pageConfig.page+1>(pageConfig.total_page-1)?(pageConfig.total_page-1):pageConfig.page+1);"></div>
                        </div>
                    </div>
                </div>`;
            let columns = ''
            if ($scope.selectItem != undefined) {
                $scope.selectItem.unit_result.forEach(function(column, index) {
                    columns += `<div class="kmi-list__column" style="flex: 0 0 100px;" ng-bind="selectItem.unit_result[${index}].unit_name"></div>`
                })
            }
            let list = $(start + columns + end);

            return list
        }

        function generateRow() {
            var row = '';
            var columns = ``
            var start = `
                <div class="kmi-list__row" ng-repeat="item in getPages(selectItem.pcs_detail, pageConfig) |orderBy:'-insert_time' track by $id(item)">
                    <div class="kmi-list__column column-border" style="flex:0 0 100px;z-index:1;position: relative;" ng-show="isSPCMode">
                        <i class="material-icons" style="color:#68bd84;" ng-show="item.is_spc_checked" >&#xE876;</i>
                    </div>
                    <div class="kmi-list__column column-border" style="flex:0 0 40px;">
                        <button class="mdl-button mdl-button--icon" ng-click="pcs_remove(item);" ng-show="!item.saved">
                            <img src="image/icons/delete.png"></img>
                        </button>
                    </div>
                    <div class="kmi-list__column column-border" style="flex:0 0 100px;" ng-bind="item.pcs_no" ng-click="selectCheck(item);"></div>
                `;
            var end = `
                    <div class="kmi-list__column column-input" style="flex: 0 0 100px;">
                        <input ng-model="item.badreason_desc" readonly="readonly" ng-click="loadBadReason(item);" ng-disabled="item.saved"></input>
                        <div class="tip"><i class="material-icons">&#xE5CF;</i></div>
                    </div>
                </div>
            `;
            if ($scope.selectItem != undefined) {
                $scope.selectItem.unit_result.forEach(function(currentValue, index) {
                    columns += `<div class="kmi-list__column column-border" style="flex: 0 0 100px;" ng-bind="item.unit_detail[${index}].material_unit_no"></div> `
                })
            }
            row = start + columns + end;

            return row;
        }

        // 20231129 add by Alan for M#: 0151319: 增加分頁功能
        $scope.pageConfig = { page: 0, page_count: 25 };
        $scope.getPages = function (list, pageConfig) {
            if (list) {
                if (pageConfig) {
                    if (list.length != 0) {
                        pageConfig.total_page = Math.ceil(list.length / pageConfig.page_count);

                        if (pageConfig.page >= pageConfig.total_page) {
                            pageConfig.page = 0;
                        }
                        var index = pageConfig.page * pageConfig.page_count;
                        return list.slice(index, index + pageConfig.page_count);
                    } else {
                        pageConfig.total_page = 1;
                        pageConfig.page = 0;
                    }
                } else {
                    return list;
                }
            } else {
                return list;
            }
        };

        $scope._event = {
            changePanelSize: {
                click: (size_type) => {
                    $scope.changePanelSize(size_type);
                }
            },
            load_B0210 :{
                click: () => {
                    $scope.load_B0210();
                }
            },
            'lot_result':{
                rowClick: (item) => {
                    $scope.clickItem(item);
                },
                checkSelect:(item)=>{
                    if($scope.selectItem){
                      return ($scope.selectItem.plot_no == item.plot_no);
                   } else {
                      return false;
                   }
                }
            },
            'E08_area_no': {
                click: () => {
                    $scope.loadArea();
                }
            },
            'E08_op_no': {
                click: () => {
                    $scope.loadOp();
                }
            },
            'E08_machine_no': {
                click: () => {
                    $scope.loadMachine();
                }
            }
            
        }
        $scope._fn = {
            'E08_StationMachinepanel_btn2': {
                click: () => {
                    $scope.changePanelSize('MAX');
                }
            },
            'E08_StationMachinepanel_btn': {
                click: () => {
                    $scope.changePanelSize('MIN');
                }
            },
            'E08_StationMachinebtn':{
                click: () => {
                    $scope.load_B0210();
                }
            },
            'E08_materialManagment':{
                click:()=>{
                        $scope.materialManagment();
                }      
           },
           'E08_operatorList':{
                click:()=>{
                  $scope.operatorList();
                }      
           },
           'E08_setting':{
                click:()=>{
                  $scope.setting();
                }      
           },
           'E08_StationMachine_materialManagment':{
                click:()=>{
                        $scope.materialManagment();
                }      
           },
           'E08_StationMachine_operatorList':{
                click:()=>{
                  $scope.operatorList();
                }      
           },
           'E08_StationMachine_setting':{
                click: () => {
                    $scope.setting();
                }
            },
            'E08_confirm': {
                click: () => {
                    $scope.confirm();
                    $scope.changeForm('E08_StationMachine');
                    if( $scope.stationMachine){
                        $scope.stationMachine.single_confirm =   $scope.E08_single_confirm == "1" ? false: true;
                    }
                }
            }
        }
    }];
});
